package org.fastsyncer.web.interceptor;

import org.apache.commons.lang.StringUtils;
import org.fastsyncer.common.util.SHA1Util;
import org.fastsyncer.web.exception.LoginException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Component
public class Ticket {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    // 会话票据
    private static final String SESSION_TOKEN = "session_token";

    // 会话过期key
    private static final String SESSION_TIMEOUT = "session_timeout";

    @Value(value = "${fastsyncer.config.login.url}")
    private String loginUrl;

    @Value(value = "${fastsyncer.config.login.session.timeout}")
    private int timeout;

    @Value(value = "${fastsyncer.config.login.username}")
    private String username;

    @Value(value = "${fastsyncer.config.login.password}")
    private String password;

    public void createTicket(HttpServletRequest request, String username, String userpwd) {
        userpwd = SHA1Util.b64_sha1(userpwd);
        if (!this.username.equals(username) || !this.password.equals(userpwd)) {
            throw new LoginException("Account or password error.");
        }
        HttpSession session = request.getSession();
        session.setAttribute(SESSION_TOKEN, username);
        session.setAttribute(SESSION_TIMEOUT, (System.currentTimeMillis() + timeout * 1000));
        logger.info("Get the ticket successfully!" + session.getId());
    }

    public void removeTicket(HttpSession session) {
        session.removeAttribute(SESSION_TOKEN);
        session.removeAttribute(SESSION_TIMEOUT);
    }

    public boolean validateTicket(HttpSession session) {
        String sessionId = (String) session.getAttribute(SESSION_TOKEN);
        // 是否存在票据信息
        if (StringUtils.isBlank(sessionId)) {
            return false;
        }
        // 票据是否过期
        if (System.currentTimeMillis() > (Long) session.getAttribute(SESSION_TIMEOUT)) {
            // 已过期,移除票据信息
            removeTicket(session);
            return false;
        }
        return true;
    }

    public String getLoginUrl() {
        return loginUrl;
    }

    public int getTimeout() {
        return timeout;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

}
